package cn.virens.web.components.weixin.handler.base;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.util.StrUtil;
import cn.virens.web.components.weixin.session.VirWxSession;
import cn.virens.web.components.weixin.session.VirWxSessionManager;
import me.chanjar.weixin.common.session.InternalSession;
import me.chanjar.weixin.common.session.WxSession;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;

public class AbstractWxMpMessageUser implements WxMpMessageUser {
	private final Logger logger = LoggerFactory.getLogger(AbstractWxMpMessageUser.class);

	private final String principal;

	private WxMpService wxMpService;
	private WxMpXmlMessage wxMpXmlMessage;

	// 请求属性
	private Map<String, Object> attributes;

	// SESSION 相关
	private VirWxSession session;
	private VirWxSessionManager sessionManager;

	public AbstractWxMpMessageUser(String principal) {
		this.principal = principal;
	}

	@Override
	public String getPrincipal() {
		return principal;
	}

	@Override
	public WxMpService getWxMpService() {
		return wxMpService;
	}

	public void setWxMpService(WxMpService wxMpService) {
		this.wxMpService = wxMpService;
	}

	@Override
	public WxMpXmlMessage getWxMpXmlMessage() {
		return wxMpXmlMessage;
	}

	public void setWxMpXmlMessage(WxMpXmlMessage wxMessage) {
		this.wxMpXmlMessage = wxMessage;
	}

	@Override
	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	@Override
	public Object getAttribute(String name) {
		return attributes.get(name);
	}

	@Override
	public void setAttribute(String name, Object value) {
		attributes.put(name, value);
	}

	@Override
	public VirWxSessionManager getSessionManager() {
		return sessionManager;
	}

	public void setSessionManager(VirWxSessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	@Override
	public final VirWxSession getSession() {
		if (session == null && sessionManager != null) {
			this.session = sessionManager.getStandardSession(principal);
		}

		return session;
	}

	@Override
	public final WxSession getSession(String sessionId) {
		if (sessionManager == null) { return null; }

		if (!StrUtil.equals(sessionId, principal)) {
			return sessionManager.getSession(sessionId);
		} else {
			return getSession();
		}
	}

	@Override
	public final void saveSession(WxSession session) {
		if (sessionManager == null) { return; }

		// 执行保存操作
		if (session instanceof VirWxSession) {
			this.sessionManager.putStandardSession((VirWxSession) session);
		} else if (session instanceof InternalSession) {
			((InternalSession) session).endAccess();
		} else {
			logger.error("The unknown method holds the session");
		}
	}

	public final void saveSession() {
		this.saveSession(session);
	}
}
